package com.wangmeng.book.uploader;

import com.wangmeng.book.dao.BaseDaoSupport;
import com.wangmeng.book.entity.*;
import com.wangmeng.book.utils.ConstValueUtils;
import com.wangmeng.book.utils.MessageDigestHelper;
import com.wangmeng.book.utils.SpringContextManager;
import net.sf.json.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.springframework.jdbc.core.JdbcTemplate;

import java.io.*;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.sql.SQLException;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * User: 王猛
 * Date: 13-10-7
 */
public class WebBookPublisher implements Serializable {
    private AtomicBoolean isLogin = new AtomicBoolean(false);
    private HttpContext context = new BasicHttpContext();
    private CookieStore cs = new BasicCookieStore();
    private String host = ConstValueUtils.WEB_HOST;
    private String userName = ConstValueUtils.WEB_USERNAME;
    private String password = ConstValueUtils.WEB_PASSWORD;

    public WebBookPublisher(String userName, String password) {
        context.setAttribute(ClientContext.COOKIE_STORE, cs);
        this.userName = userName;
        this.password = password;
    }

    public boolean login() {
        HttpClient client = new DefaultHttpClient();
        Long time = new Date().getTime() / 1000;
        String tp = MessageDigestHelper.digestBySHA(password + time.toString());
        HttpGet request = new HttpGet(host + "/index.php/Home/Index/login?XDEBUG_SESSION_START=xdebug&username=" + userName + "&salt=" + time.toString() + "&password=" + tp);
        HttpResponse response = null;
        try {
            response = client.execute(request, context);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                ByteArrayOutputStream bout = new ByteArrayOutputStream();
                response.getEntity().writeTo(bout);
                String jsonStr = bout.toString().trim();
                JSONObject result = JSONObject.fromObject(jsonStr);
                if (result != null && result.getInt("code") == 0) {
                    isLogin.set(true);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            client.getConnectionManager().shutdown();
        }
        return isLogin.get();
    }

    public void publish(BookDoc bd) {
        if (isLogin.get() && bd != null && bd.getId() > 0) {
            try {
                Map data = new HashMap();
                data.put("op_type", 1);//新增
                data.put("oid", bd.getId());
                data.put("name", bd.getName());
                data.put("author", bd.getAuthor());
                data.put("author_brief", bd.getAuthorBrief());
                data.put("publisher", bd.getPublisher());
                data.put("book_brief", bd.getBookBrief());
                data.put("part_name", bd.getPartition());
                data.put("status", bd.getStatus());
                data.put("type", bd.getType());
                data.put("word_num", bd.getWordNum());
                data.put("has_icon", bd.getHasIcon());
                data.put("view_count", 1);
                File temp = File.createTempFile("tmp", "img");
                FileOutputStream bout = new FileOutputStream(temp);
                if (bd.getHasIcon()) {
                    try {
                        InputStream in = bd.getIcon().getBinaryStream();
                        byte[] buffer = new byte[4096];
                        int len = 0;
                        while ((len = in.read(buffer)) > 0) {
                            bout.write(buffer, 0, len);
                        }
                        in.close();
                        bout.flush();
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        bout.close();
                    }
                } else {
                    temp = null;
                }
                List<Map> sectionMap = new ArrayList<Map>();
                data.put("section_list", sectionMap);
                List<Map> partMap = new ArrayList<Map>();
                data.put("part_list", partMap);
                BaseDaoSupport baseDaoSupport = SpringContextManager.getContext().getBean(BaseDaoSupport.class);
                List<BookDocSection> sectionList = baseDaoSupport.listEntityByCondition(BookDocSection.class, "and bookId = ? and status = 0 ", new Object[]{bd.getId()});
                for (BookDocSection bds : sectionList) {
                    Map sMap = new HashMap();
                    sMap.put("oid", bds.getId());
                    sMap.put("section_name", bds.getName());
                    sMap.put("book_id", bds.getBookId());
                    sMap.put("section_order", bds.getOrder());
                    sMap.put("status", bds.getStatus());
                    sectionMap.add(sMap);
                    List<BookDocPart> partList = baseDaoSupport.listEntityByCondition(BookDocPart.class, "and sectionId = ? and status = 0 ", new Object[]{bds.getId()});
                    for (BookDocPart part : partList) {
                        Map pMap = new HashMap();
                        pMap.put("oid", part.getId());
                        pMap.put("title", part.getTitle());
                        pMap.put("store_type", part.getStoreType());
                        pMap.put("content", part.getContent());
                        pMap.put("path", part.getPath());
                        pMap.put("section_id", part.getSectionId());
                        pMap.put("part_order", part.getOrder());
                        pMap.put("status", part.getStatus());
                        partMap.add(pMap);
                    }
                }
                HttpClient client = new DefaultHttpClient();
                HttpPost post = new HttpPost(host + "/index.php/Admin/Index/publish");
                String json = JSONObject.fromObject(data).toString();
                MultipartEntity entity = new MultipartEntity();
                entity.addPart("data", new StringBody(URLEncoder.encode(json, "UTF-8")));
                if (temp != null) {
                    entity.addPart("file", new FileBody(temp));
                }
                post.setEntity(entity);
                HttpResponse resp = null;
                try {
                    resp = client.execute(post, context);
                    if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                        ByteArrayOutputStream rout = new ByteArrayOutputStream();
                        resp.getEntity().writeTo(rout);
                        String result = rout.toString().trim();
                        JSONObject rObj = JSONObject.fromObject(result);
                        if (rObj != null && rObj.getInt("code") == 0) {
                            bd.setApproveStatus(ConstValueUtils.APPROVE_PUBLISH_SUCCESS);
                            baseDaoSupport.saveEntity(bd);
                            String sqlUp = "update book_document_section set status = 1 where status = 0 and book_id = ? ";
                            JdbcTemplate jt = SpringContextManager.getContext().getBean(JdbcTemplate.class);
                            jt.update(sqlUp,new Object[]{bd.getId()});
                            String sqlUpPart = "update book_document_part set status = 1 where status = 0 and section_id in \n" +
                                    "(select oid from book_document_section where book_id = ? )";
                            jt.update(sqlUpPart,new Object[]{bd.getId()});
                        }
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                } finally {
                    client.getConnectionManager().shutdown();
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    public void update(BookDoc bd) {
        if (isLogin.get() && bd != null && bd.getId() > 0) {
            try {
                Map data = new HashMap();
                data.put("op_type", 2);//更新
                data.put("oid", bd.getId());
                data.put("part_name", bd.getPartition());
                data.put("word_num", bd.getWordNum());
                List<Map> sectionMap = new ArrayList<Map>();
                data.put("section_list", sectionMap);
                List<Map> partMap = new ArrayList<Map>();
                data.put("part_list", partMap);
                BaseDaoSupport baseDaoSupport = SpringContextManager.getContext().getBean(BaseDaoSupport.class);
                List<BookDocSection> sectionList = baseDaoSupport.listEntityByCondition(BookDocSection.class, "and bookId = ? and status = 0 ", new Object[]{bd.getId()});
                for (BookDocSection bds : sectionList) {
                    Map sMap = new HashMap();
                    sMap.put("oid", bds.getId());
                    sMap.put("section_name", bds.getName());
                    sMap.put("book_id", bds.getBookId());
                    sMap.put("section_order", bds.getOrder());
                    sMap.put("status", bds.getStatus());
                    sectionMap.add(sMap);
                    List<BookDocPart> partList = baseDaoSupport.listEntityByCondition(BookDocPart.class, "and sectionId = ? and status = 0 ", new Object[]{bds.getId()});
                    for (BookDocPart part : partList) {
                        Map pMap = new HashMap();
                        pMap.put("oid", part.getId());
                        pMap.put("title", part.getTitle());
                        pMap.put("store_type", part.getStoreType());
                        pMap.put("content", part.getContent());
                        pMap.put("path", part.getPath());
                        pMap.put("section_id", part.getSectionId());
                        pMap.put("part_order", part.getOrder());
                        pMap.put("status", part.getStatus());
                        partMap.add(pMap);
                    }
                }
                HttpClient client = new DefaultHttpClient();
                HttpPost post = new HttpPost(host + "/index.php/Admin/Index/publish");
                String json = JSONObject.fromObject(data).toString();
                MultipartEntity entity = new MultipartEntity();
                entity.addPart("data", new StringBody(URLEncoder.encode(json, "UTF-8")));
                post.setEntity(entity);
                HttpResponse resp = null;
                try {
                    resp = client.execute(post, context);
                    if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                        ByteArrayOutputStream rout = new ByteArrayOutputStream();
                        resp.getEntity().writeTo(rout);
                        String result = rout.toString().trim();
                        JSONObject rObj = JSONObject.fromObject(result);
                        if (rObj != null && rObj.getInt("code") == 0) {
                            bd.setApproveStatus(ConstValueUtils.APPROVE_PUBLISH_SUCCESS);
                            baseDaoSupport.saveEntity(bd);
                            String sqlUp = "update book_document_section set status = 1 where status = 0 and book_id = ? ";
                            JdbcTemplate jt = SpringContextManager.getContext().getBean(JdbcTemplate.class);
                            jt.update(sqlUp,new Object[]{bd.getId()});
                            String sqlUpPart = "update book_document_part set status = 1 where status = 0 and section_id in \n" +
                                    "(select oid from book_document_section where book_id = ? ) ";
                            jt.update(sqlUpPart,new Object[]{bd.getId()});
                        }
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                } finally {
                    client.getConnectionManager().shutdown();
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
}
